// 1.下包
// 2.导包
import axios from "axios";
import { getItem } from "./localData";
import { Dialog } from "vant";
import router from "../router/index";

// 3.配置基准路径(根地址)
// axios.defaults.baseURL = "http://157.122.54.189:9083";
axios.defaults.baseURL = "http://localhost:3000";
axios.interceptors.request.use(
  (config) => {
    //   console.log(config);
    const token = getItem();
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    // console.log('服务器响应数据后，axios 会自动调用的函数', response)
    if (response.data.message === "用户信息验证失败") {
      Dialog.confirm({
        title: "未登录",
        message: "需要登录后再操作",
        confirmButtonText: "去登录",
        cancelButtonText: "残忍拒绝",
      })
        .then(() => {
          // on confirm
          router.push({ path: "/login" });
        })
        .catch(() => {
          // on cancel
        });
    }
    // 返回的数据
    return response;
  },
  (error) => Promise.reject(error)
);
// 4.暴露
export default axios;
